package fms.webservice.server.parser;

import fms.webservice.server.common.*;
import fms.webservice.server.dao.DataReaderDao;
import fms.webservice.server.util.BuildSqlUtil;
import fms.webservice.server.util.ObjectUtil;
import fms.webservice.server.util.XmlUtil;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2014/7/16.
 */
public class AutoPosRequestParser implements IRequestParser  {
    private static Logger logger = Logger.getLogger(AutoPosRequestParser.class);

    public Response parser(Request autoPosRequest) {
        Response response = new Response();
        response.setServiceType(autoPosRequest.getServiceType());
        response.setVersion(autoPosRequest.getVersion());
        AutoPosResponseXML autoPosResponseXML = new AutoPosResponseXML();
        AutoPosRequestXML autoPosRequestXML = XmlUtil.unMarshallAutoPosRequest(autoPosRequest.getRequestXML());
        ErrorLevel el = new ErrorLevel();
        try {
            DataReaderDao dr = null;
            try {
                dr = new DataReaderDao();
            } catch (ClassNotFoundException e1) {
                // TODO Auto-generated catch block
//                autoPosRequestXML.e(el.DBError);
                logger.error(e1.getMessage());
                return response;
            }

            String sql = BuildSqlUtil.buildSQL(autoPosRequestXML);
            List li = null;
            try {
                li = dr.getRawMsgList(sql);
            } catch (ClassNotFoundException e) {
                logger.error(e.getMessage());
                return response;
            } catch (IOException e) {
                logger.error(e.getMessage());
                return response;
            }
            String cptName = "";
            Iterator it = li.iterator();
            while (it.hasNext()) {
                Map hm = (Map) it.next();
                if (!ObjectUtil.isBlank(hm.get("CPT_NAME").toString())) {
                    cptName += "" + hm.get("CPT_NAME").toString() + ".";
                }
            }
            if(cptName.contains(".")){
                cptName = cptName.substring(0, cptName.length() - 1);
            }
            autoPosResponseXML.setCptname(cptName);
            autoPosResponseXML.setAircraftid(autoPosRequestXML.getAircraftid());
            autoPosResponseXML.setAirlines(autoPosRequestXML.getFlightID().substring(0,2));
        } catch (SQLException e) {
            logger.error(e.getMessage());
            return response;
        }
        response.setResponseXML(XmlUtil.marshallAutoPosResponse(autoPosResponseXML));
        return response;
    }
}
